package com.joker.aigc.chat.service.event.listener;


import com.joker.aigc.chat.dao.ContactDao;
import com.joker.aigc.chat.dao.RoomDao;
import com.joker.aigc.chat.domain.entity.Message;
import com.joker.aigc.chat.domain.entity.websocket.WebSocketMessageSendVo;
import com.joker.aigc.chat.mapper.MessageMapper;
import com.joker.aigc.chat.service.PushService;
import com.joker.aigc.chat.service.adapter.WebSocketAdapter;
import com.joker.aigc.chat.service.event.MessageSendEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import java.util.Collections;

/**
 * 消息发送监听器
 *
 * @author zhongzb create on 2022/08/26
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MessageSendListener {

    final MessageMapper messageMapper;
    final PushService pushService;
    final RoomDao roomDao;
    final ContactDao contactDao;


    /**
     * 发送消息
     *
     * @param event 发送消息的事件
     */
    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT, classes = MessageSendEvent.class, fallbackExecution = true)
    public void messageRoute(MessageSendEvent event) {
        Message message = event.getMessage();
        WebSocketMessageSendVo webSocketMessageSendVo = new WebSocketMessageSendVo();
        webSocketMessageSendVo.setMsgId(message.getId());
        // step 1:更新用户的房间信息，刷新最近的交流时间
        roomDao.refreshActiveTime(message.getRoomId(), message.getId(), message.getCreateTime());
        // step 2:推送用户的消息
        pushService.sendMessage(WebSocketAdapter.buildMsgSend(webSocketMessageSendVo));
        // step 3: 刷新用户的会话时间
        contactDao.refreshOrCreateActiveTime(
                message.getRoomId(),
                message.getId(),
                message.getCreateTime()
        );
        // step 4: 刷新发送消息的人的 阅读时间
        contactDao.refreshReadTime(
                message.getRoomId(),
                Collections.singletonList(message.getFromUid()),
                message.getId(),
                message.getCreateTime()
        );
    }
}
